package LW.org.DToperation;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

import LW.org.model.Users;

public class operation {
	
	private SessionFactory factroy = null;
	private Session session=null;
	private Transaction tx = null;
	
	public void config()
	{
		Configuration cfg = new Configuration().configure();
		StandardServiceRegistryBuilder buidler = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties());
		StandardServiceRegistry service = buidler.build();
		factroy = cfg.buildSessionFactory(service);
		session = factroy.openSession();
		tx = session.beginTransaction();
	}
	
	public Users check(int ID)
	{
		config();
		Query query = session.createQuery("from Users o where o.ID=?");
		query.setInteger(0, ID);
		Users o = (Users)query.list().get(0);
		if(o!=null)
		{
			return o;
		}
		return null;
	}
	
	public Users addNewone(Users newone)
	{
		config();
		Users newone_return = new Users();
		try {
			Users newGuy = new Users();
			newGuy.setName(newone.getName());
			System.out.println(newone.getPassword());
			newGuy.setPassword(newone.getPassword());
			session.save(newGuy);
			tx.commit();
			Query query = session.createQuery("from Users o where o.name=?");
			query.setString(0, newone.getName());
			newone_return = (Users)query.list().get(0);
			return newone_return;
		} catch (Exception e) {
			tx.rollback();
			System.out.println("addNew has error : "+e.toString());
			return null;
		}
		finally {
			session.clear();
			session.close();
			factroy.close();
		}
	}
}
